var Uploader = (function () {
	function Module(uploadBtnSel, uploadUrl, swfUrl, fn, uploadSuccessFn) {
		this.uploadBtnSel = uploadBtnSel;
		this.uploadUrl = uploadUrl;
		this.swfUrl = swfUrl;
		this.fn = fn;
		this.uploadSuccessFn = uploadSuccessFn;
		this.uploader = null;
		this.init();
	}

	Module.prototype.init = function() {
		var me = this,
			uploader,
			ratio = window.devicePixelRatio || 1,
		// 缩略图大小
			thumbnailWidth = 100 * ratio,
			thumbnailHeight = 100 * ratio;

		me.uploader = uploader = WebUploader.create({
			auto: true,
			swf: me.swfUrl,
			// 文件接收服务端。
			server: me.uploadUrl,
			// 选择文件的按钮。可选。
			// 内部根据当前运行是创建，可能是input元素，也可能是flash.
			pick: me.uploadBtnSel,
			// 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
			resize: false,
			accept: {
				title: 'Images',
				extensions: 'gif,jpg,jpeg,bmp,png',
				mimeTypes: 'image/*'
			}
		});

		uploader.on('fileQueued', function (file) {
			var $li = $(
					'<div id="' + file.id + '" class="file-item thumbnail">' +
					'<img title="' + file.name + '">' +
					'</div>'
				),
				$img = $li.find('img');

			me.fn && me.fn.call(this, $li, file);

			// 创建缩略图
			uploader.makeThumb(file, function (error, src) {
				if (error) {
					$img.replaceWith('<span>不能预览</span>');
					return;
				}
				$img.attr('src', src);
			}, thumbnailWidth, thumbnailHeight);
		});

		uploader.on('uploadProgress', function (file, percentage) {
			var $li = $('#' + file.id),
				$percent = $li.find('.progress .progress-bar');
			// 避免重复创建
			if (!$percent.length) {
				$percent = $('<div class="progress progress-striped active">' +
					'<div class="progress-bar" role="progressbar" style="width: 0%">' +
					'</div>' +
					'</div>').appendTo($li).find('.progress-bar');
			}

			$li.find('p.state').text('上传中');
			$percent.css('width', percentage * 100 + '%');
		});


		uploader.on('uploadSuccess', function (file, resp) {
			me.uploadSuccessFn && me.uploadSuccessFn.call(this, file, resp);
		});

		uploader.on('uploadError', function (file) {
			$('#' + file.id).find('p.state').text('上传出错');
		});

		uploader.on('uploadComplete', function (file) {
			$('#' + file.id).find('.progress').fadeOut();
		});
	};

	return Module;
})();